/*
 * @Author: atony2099
 * @Date: 2019-02-14 14:38:09
 * @Last Modified by: atony2099
 * @Last Modified time: 2019-02-15 05:08:37
 */

'use strict';

const _ = require('lodash');

module.exports = () => {
  return async (ctx, next) => {
    const {
      request,
      service: { user },
    } = ctx;
    const token =
      request.query.token || request.body.token || ctx.request.headers.token;

    if (token) {
      let userInfo = await user.getUserByQuery({ token });
      userInfo = _.pick(userInfo, [
        'username',
        'loginname',
        '_id',
        'lastSignDate',
        'continusDay',
        'goldCount',
      ]);
      if (!userInfo) {
        ctx.toError(401, 'invalidated token');
        return;
      }
      ctx.$userInfo = userInfo;
      await next();
    } else {
      ctx.toError(401, 'invalidated tokne');
    }
  };
};
